<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 820px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <template class="flex">
        <el-form-item label="计划编号" prop="planCode">
          <el-input
            v-model="formData.planCode"
            placeholder="系统自动生成"
            class="!w-260px"
            disabled
          />
        </el-form-item>
        <el-form-item label="所属公司" prop="airlineComp">
          <el-select
            v-model="formData.airlineComp"
            placeholder="请选择所属航空公司"
            class="!w-260px"
          >
            <el-option
              v-for="item in getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_ID)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <template class="flex">
        <el-form-item label="航班号" prop="flightNo">
          <el-input v-model="formData.flightNo" placeholder="请输入航班号" class="!w-260px" />
        </el-form-item>
        <el-form-item label="起飞时间" prop="depTime">
          <el-time-picker
            v-model="formData.depTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="选择起飞时间"
            clearable
            class="!w-260px"
          />
        </el-form-item>
      </template>
      <ContentWrap>
        <div class="meal-config-block">
          <div class="block-title">前舱配置</div>
          <el-form-item label="前舱人数" prop="frontCabinQty">
            <el-input
              placeholder="请输入人数"
              v-model.number="formData.frontCabinQty"
              class="!w-240px"
            />
          </el-form-item>
          <TextileProducePlanItem
            title="前舱"
            prefix="front"
            :model="formData"
            :SimpleList="SimpleList"
        /></div>
        <div class="meal-config-block">
          <div class="block-title">中舱配置</div>
          <el-form-item label="中舱人数" prop="frontCamiddleCabinQtybinQty">
            <el-input
              placeholder="请输入人数"
              v-model.number="formData.middleCabinQty"
              class="!w-240px"
            />
          </el-form-item>
          <TextileProducePlanItem
            title="中舱"
            prefix="middle"
            :model="formData"
            :SimpleList="SimpleList"
          />
        </div>
        <div class="meal-config-block">
          <div class="block-title">后舱配置</div>
          <el-form-item label="后舱人数" prop="rearCabinQty">
            <el-input
              placeholder="请输入人数"
              v-model.number="formData.rearCabinQty"
              class="!w-240px"
            />
          </el-form-item>
          <TextileProducePlanItem
            title="后舱"
            prefix="rear"
            :model="formData"
            :SimpleList="SimpleList"
          />
        </div>
      </ContentWrap>
      <el-form-item label="特殊说明" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入特殊说明" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TextileProducePlanApi, TextileProducePlanVO } from '@/api/acm/textileproduceplan'
import { OnboardSupplyApi } from '@/api/acm/onboardsupply'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import TextileProducePlanItem from './TextileProducePlanItem.vue'

/** 航机管理-机供品生产计划 表单 */
defineOptions({ name: 'OnboardSupplyPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  planCode: undefined,
  flightNo: undefined,
  depTime: undefined,
  airlineComp: undefined,
  frontCabinQty: undefined,
  frontDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
  middleCabinQty: undefined,
  middleDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
  rearCabinQty: undefined,
  rearDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
  remarks: undefined,
  markStatus: undefined,
  status: undefined
})
// 自定义校验函数：校验detailList数组中每一项的supplyId和supplyQty
const validateDetailList = (rule: any, value: any[], callback: any, cabinName: string) => {
  // 遍历数组中的每一项
  for (let i = 0; i < value.length; i++) {
    const item = value[i]
    // 检查纺织品ID是否选择
    if (!item.supplyId) {
      return callback(new Error(`${cabinName}第${i + 1}行：请选择纺织品`))
    }
    if (item.supplyQty === undefined || item.supplyQty === null || item.supplyQty <= 0) {
      return callback(new Error(`${cabinName}第${i + 1}行：请填写有效的数量`))
    }
  }
  // 所有项校验通过
  callback()
}
const formRules = reactive({
  airlineComp: [{ required: true, message: '航空公司不能为空', trigger: 'blur' }],
  flightNo: [{ required: true, message: '航班号不能为空', trigger: 'blur' }],
  depTime: [{ required: true, message: '起飞时间不能为空', trigger: 'blur' }],
  frontCabinQty: [{ required: true, message: '人数不能为空', trigger: 'blur' }],
  middleCabinQty: [{ required: true, message: '人数不能为空', trigger: 'blur' }],
  rearCabinQty: [{ required: true, message: '人数不能为空', trigger: 'blur' }],
  frontDetailList: [
    {
      validator: (rule: any, value: any[], callback: any) => {
        validateDetailList(rule, value, callback, '前舱')
      },
      trigger: ['change', 'blur'] // 当数据变化或失去焦点时触发校验
    }
  ],
  middleDetailList: [
    {
      validator: (rule: any, value: any[], callback: any) => {
        validateDetailList(rule, value, callback, '中舱')
      },
      trigger: ['change', 'blur']
    }
  ],

  rearDetailList: [
    {
      validator: (rule: any, value: any[], callback: any) => {
        validateDetailList(rule, value, callback, '后舱')
      },
      trigger: ['change', 'blur']
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  getSimpleList()
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TextileProducePlanApi.getTextileProducePlan(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取机供品精简列表 */
const SimpleList = ref([])
const getSimpleList = async () => {
  try {
    const res = await OnboardSupplyApi.getOnboardSupplySimpleList({ category: 2, name: '' })
    SimpleList.value = res
    console.log(SimpleList.value)
  } finally {
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TextileProducePlanVO
    if (formType.value === 'create') {
      await TextileProducePlanApi.createTextileProducePlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await TextileProducePlanApi.updateTextileProducePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planCode: undefined,
    flightNo: undefined,
    depTime: undefined,
    airlineComp: undefined,
    frontCabinQty: undefined,
    frontDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
    middleCabinQty: undefined,
    middleDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
    rearCabinQty: undefined,
    rearDetailList: [{ id: undefined, supplyId: undefined, supplyQty: undefined }],
    remarks: undefined,
    markStatus: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped >
.meal-config-block {
  margin-bottom: 24px;
}
.block-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}
.row-group {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
</style>